import type {AxiosInstance} from "axios";
import axios from "axios";
// 在vue文件中这样引入没事，但是在ts文件中这样引用就会报错，原因不明
// @ts-ignore
import {ElLoading, ElMessage} from 'element-plus';
// import {useRouter} from "vue-router";

import router from '@/router/index.ts'

// const router = useRouter()

let loadingInstance: any = null;//蒙版实例
let timer: any = null;//定时器

// 创建一个接收文件的axios实例


// 创建axios实例
export const request: AxiosInstance = axios.create({
    //baseURL: 'http://127.0.0.1:8005/api',
    baseURL: import.meta.env.VITE_APP_BASE_API,
    //baseURL: 'http://test.silyahuukou.cn:8005/api',
    timeout: 100000,
    headers: {
        "Content-Type": "application/json;charset=UTF-8",
        "Access-Control-Allow-Headers": "Accept, token, Content-Type"
    },
});
request.interceptors.request.use(
    (config: any) => {
        // 判定是否打开遮罩
        if (timer !== null) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            //如果存在则关闭
            if (loadingInstance !== null) {
                loadingInstance.close();
            }
            loadingInstance = ElLoading.service({
                lock: true,
                text: '努力加载中！',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.3)'
            });
        }, 500);
        // 添加token到header中
        let temp1 = localStorage.getItem('token')
        let temp2 = sessionStorage.getItem('token')
        if (temp1 !== null) {
            config.headers.token = temp1
        } else {
            config.headers.token = temp2
        }

        return config;
    },
    (error) => {
        console.log(error)
        return Promise.reject()
    }
)


/**
 * 拦截器
 *
 */
request.interceptors.response.use(response => {
    // 请求返回后，关闭loading
    clearTimeout(timer);
    timer = null;
    if (loadingInstance !== null) {
        loadingInstance.close();
    }

    // console.log('response.data：', response.data)

    // 处理业务错误
    // 如果成功
    if (response.data.success) {
        return response.data;
    // 如果失败且失败原因为无权限
    } else if (response.data.error.code === 6004) {
        ElMessage.error(`错误${response.data.error?.code}：${response.data.error.message}`)
        router.push({name: 'login'}).then()
        return Promise.reject()
    // 其他失败原因
    } else {
        // console.log(response.data)
        ElMessage.error(`错误${response.data.error?.code}：${response.data.error.message}`)
        return Promise.reject()
        // throw new Error()
    }
}, error => {
    // 请求返回后，关闭loading
    clearTimeout(timer);
    timer = null;
    if (loadingInstance !== null) {
        loadingInstance.close();
    }
    // 处理传输层错误
    if (error && error.response) {
        switch (error.response.status) {
            case 400:
                error.message = '400 错误请求'
                break;
            case 401:
                error.message = '401 未授权，请重新登录'
                break;
            case 403:
                error.message = '403 拒绝访问'
                break;
            case 404:
                error.message = '404 请求错误，未找到该资源'
                break;
            case 405:
                error.message = '405 请求方法未允许'
                break;
            case 408:
                error.message = '408 请求超时'
                break;
            case 500:
                error.message = '500 服务器端出错'
                break;
            case 501:
                error.message = '501 网络未实现'
                break;
            case 502:
                error.message = '502 网络错误'
                break;
            case 503:
                error.message = '503 服务不可用'
                break;
            case 504:
                error.message = '504 网络超时'
                break;
            case 505:
                error.message = '505 http版本不支持该请求'
                break;
            default:
                error.message = `连接错误${error.response.status}`
        }
    } else {
        error.message = '连接服务器失败'
    }
    ElMessage.error(`错误信息: ${error.message}`)

    throw error.response
})

export default request
